package com.jsmtr.rms.utils;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Calendar;
import java.util.Random;

import org.jsoup.Jsoup;
import org.jsoup.safety.Whitelist;

public class StringTools {

    public static boolean notEmpty(Object obj) {
        if (obj != null && !obj.equals("")) {
            return true;
        }
        return false;
    }

    public static boolean trimNotEmpty(Object obj) {
        if (obj != null && !obj.toString().trim().equals("")) {
            return true;
        }
        return false;
    }

    public static String nullToStr(Object obj) {
        if (obj != null && !obj.toString().trim().equals("")) {
            return obj.toString();
        }
        return "";
    }

    public static String nullToStr(Object obj, String str) {
        if (obj != null && !obj.toString().trim().equals("")) {
            return obj.toString();
        }
        return str;
    }

    public static String subStrings(String str, int len) {
        if (trimNotEmpty(str) && str.length() > len) {
            return str.substring(0, len - 1) + "...";
        } else {
            return str;
        }
    }

    /**
     * 过滤html标签
     *
     * @param htmlStr 需要过滤html标签的字符串
     * @return
     */
    public static String delHTML(String htmlStr) {
        try {
            Whitelist wlist = new Whitelist();
            return Jsoup.clean(htmlStr, wlist);
        } catch (Exception ex) {
            System.out.println(ex);
            return htmlStr;
        }
    }


    /**
     * 过滤html标签（保留tag标签）
     *
     * @param htmlStr 需要过滤html标签的字符串
     * @param tag     需要保留的html标签
     * @return
     */
    public static String delHTML(String htmlStr, String tag) {
        try {
            Whitelist wlist = new Whitelist();
            wlist.addTags(tag);
            return Jsoup.clean(htmlStr, wlist);
        } catch (Exception ex) {
            System.out.println(ex);
            return htmlStr;
        }
    }


    /***MD5加密************************开始*/

    // 全局数组
    private final static String[] strDigits = {"0", "1", "2", "3", "4", "5",
            "6", "7", "8", "9", "a", "b", "c", "d", "e", "f"};

    // 返回形式为数字跟字符串
    private static String byteToArrayString(byte bByte) {
        int iRet = bByte;
        // System.out.println("iRet="+iRet);
        if (iRet < 0) {
            iRet += 256;
        }
        int iD1 = iRet / 16;
        int iD2 = iRet % 16;
        return strDigits[iD1] + strDigits[iD2];
    }


    // 转换字节数组为16进制字串
    private static String byteToString(byte[] bByte) {
        StringBuffer sBuffer = new StringBuffer();
        for (int i = 0; i < bByte.length; i++) {
            sBuffer.append(byteToArrayString(bByte[i]));
        }
        return sBuffer.toString();
    }

    public static String GetMD5Code(String strObj) {
        String resultString = null;
        try {
            resultString = new String(strObj);
            MessageDigest md = MessageDigest.getInstance("MD5");
            // md.digest() 该函数返回值为存放哈希值结果的byte数组
            resultString = byteToString(md.digest(strObj.getBytes()));
        } catch (NoSuchAlgorithmException ex) {
            ex.printStackTrace();
        }
        return resultString;
    }

    /***MD5加密************************结束*/


    /**
     * 生成随机数
     **/
    public static String getRandNum(int len) {
        try {
            Random RANDOM = new Random();
            StringBuilder Str = new StringBuilder();
            for (int i = 0; i < len; i++) {
                Str.append(RANDOM.nextInt(10));
            }
            return Str.toString();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 获取文件扩展名
     *
     * @param file
     * @return
     */
    public static String getFileExtension(String fileName) {
        if (fileName.lastIndexOf(".") != -1 && fileName.lastIndexOf(".") != 0) {
            String result = fileName.substring(fileName.lastIndexOf("."));
            return result.toLowerCase();
        } else {
            return "";
        }
    }

    /**
     * 身份证号求年龄
     *
     * @param cardno
     * @return
     */
    public static Integer CardNo2Age(String cardno) {
        try {
            cardno = cardno.substring(6, cardno.length() - 8);
            Calendar cal = Calendar.getInstance();
            java.util.Date date = cal.getTime();
            String s1 = date.toString();
            String s2 = (String) s1.subSequence(s1.length() - 4, s1.length());

            return Integer.parseInt(s2) - Integer.parseInt(cardno);
        } catch (Exception e) {
            return 0;
        }

    }

    /**
     * 中文标点符号转英文字标点符号
     *
     * @param str
     *            原字符串
     * @return str 新字符串
     */
    public static final String cToe(String str) {
        String[] regs = { "！", "，", "。", "；", "~", "《", "》", "（", "）", "？",
                "”", "｛", "｝", "“", "：", "【", "】", "”", "‘", "’", "!", ",",
                ".", ";", "`", "<", ">", "(", ")", "?", "'", "{", "}", "\"",
                ":", "{", "}", "\"", "\'", "\'" };
        for (int i = 0; i < regs.length / 2; i++) {
            str = str.replaceAll(regs[i], regs[i + regs.length / 2]);
        }
        return str;
    }

    /**
     * 判断字符串是否为空或空字符串
     *
     * @param str
     *            原字符串
     * @return
     */
    public static boolean isEmpty(String str) {
        return str == null || "".equals(str);
    }


    /**
     * 全角转半角:
     *
     * @param fullStr
     * @return
     */
    public static final String full2Half(String fullStr) {
        if (isEmpty(fullStr)) {
            return fullStr;
        }
        char[] c = fullStr.toCharArray();
        for (int i = 0; i < c.length; i++) {
            System.out.println((int) c[i]);
            if (c[i] >= 65281 && c[i] <= 65374) {
                c[i] = (char) (c[i] - 65248);
            } else if (c[i] == 12288) { // 空格
                c[i] = (char) 32;
            }
        }
        return new String(c);
    }
    /**
     * 半角转全角
     *
     * @param halfStr
     * @return
     */
    public static final String half2Full(String halfStr) {
        if (isEmpty(halfStr)) {
            return halfStr;
        }
        char[] c = halfStr.toCharArray();
        for (int i = 0; i < c.length; i++) {
            if (c[i] == 32) {
                c[i] = (char) 12288;
            } else if (c[i] < 127) {
                c[i] = (char) (c[i] + 65248);
            }
        }
        return new String(c);
    }


}